package com.yixiu.study.juc.countdownlatch;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @CalssName T01_CountDownLatch
 * @Description
 * @Author yixiu
 * @Date 2021/6/24 10:03
 * @Verison num1.0
 **/
public class T01_CountDownLatch {

    public static void main(String[] args) {
        usingCountDownLatch();
//        usingJoin();
    }

    private static void usingCountDownLatch(){
        Thread[] threads = new Thread[100];
        CountDownLatch latch = new CountDownLatch(threads.length);

        for(int i=0; i<threads.length; i++){
            threads[i] = new Thread(() ->{
                int result = 0;
                for(int j=0; j<100000; j++){
                    result += j;
                }
                System.out.println(result);
                latch.countDown();
            });
        }

        for(int i=0; i<threads.length; i++){
            threads[i].start();
        }

        try {
            System.out.println("latch await start");
            latch.await(20, TimeUnit.SECONDS);
            System.out.println("latch await end");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("end latch");
    }


    private static void usingJoin(){
        Thread[] threads = new Thread[100];

        for(int i=0; i<threads.length; i++){
            threads[i] = new Thread(() ->{
                int result = 0;
                for(int j=0; j<100000; j++){
                    result += j;
                }
            });
        }

        for(int i=0; i<threads.length; i++){
            threads[i].start();
        }

        for(int i=0; i<threads.length; i++){
            try {
                System.out.println("join start");
                threads[i].join();
                System.out.println("join end");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }


        System.out.println("end join");
    }

}
